<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\FlowTest;
use Flow\Flow;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\UserPower;

class FlowtmpController extends ControllerBase
{

    public function templateAction()
    {
        $this->view->pick('flowtmp/template');
        Main::showNavPosition();
        Assets::xhFlow();
        Assets::easyUI('js/flowtmp/template.js');
        $listSearchArr = $listButtonArr = [];
        $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'添加', 'plain'=>'true', 'icon'=>'fa-plus'];
        $formButtonArr = Main::createFormButton('test');
        $formButtonArr[] = ['id' => 'bt_form_submit', 'text' => '提交'];
        $this->view->setVars([
            'List'          => Template::createList('list', 'Flowtmp_Template', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'Form' => Template::createForm('Flowtmp_Template'),
            'FormButton' => Template::createButtonToolBar($formButtonArr)
        ]);
    }

    public function getTemplateAction()
    {
        return $this->sendJsonResponse(Main::runModelPage('Admin\\Models\\FlowTest'));
    }

    public function createTmpAction()
    {
        try {
            $this->db->begin();
            $obj = new FlowTest();
            $obj->assign($this->request->getPost());
            if (!$obj->save()) {
                throw new \Exception('保存失败');
            }
            $flow = new Flow('flow', 'flow_test');
            if (!$flow->saveFlow($obj->id)) {
                throw new \Exception('流程保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse($obj->id);
        }
        catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    public function getTemplateInfoAction()
    {
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $obj = FlowTest::findFirst($id);
        if (!$obj) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        return $this->sendJsonResponse($obj);
    }

}

